package com.hc.conferencecheck.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hc.conferencecheck.entity.*;
import com.hc.conferencecheck.mapper.AttendRecordBranchMapper;
import com.hc.conferencecheck.mapper.AttendRecordMapper;
import com.hc.conferencecheck.mapper.ConventionerMapper;
import com.hc.conferencecheck.service.ConventionerService;
import com.hc.conferencecheck.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 与会者service实现类
 */
//开启事务管理
@Transactional
@Service
public class ConventionerServiceImpl implements ConventionerService {
    public static final Logger logger = LoggerFactory.getLogger(ConventionerServiceImpl.class);
    @Resource
    private ConventionerMapper conventionerMapper;
    @Resource
    private AttendRecordMapper attendRecordMapper;
    @Resource
    private AttendRecordBranchMapper attendRecordBranchMapper;

    /**
     * 根据手机号查询用户
     */
    public ResultMsg selectConventionerByPhoneNumber(Map<String, Object> params) {
        Object phoneNumberObj = params.get("phoneNumber");
        String phoneNumber = phoneNumberObj.toString();

        ConventionerExample example = new ConventionerExample();
        ConventionerExample.Criteria criteria = example.createCriteria();
        criteria.andPhoneNumberEqualTo(phoneNumber);

        List<Conventioner> conventioners = conventionerMapper.selectByExample(example);

        if (conventioners != null && conventioners.size() > 0) {
            Conventioner conventioner = conventioners.get(0);
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), conventioner);
        } else {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "查无此用户");
        }
    }

    /**
     * 删除用户信息
     */
    public ResultMsg deleteConventioner(Map<String, Object> params) {
        //获取用户ID
        Object conventionerObj = params.get("conventionerId");
        int conventionerId = Integer.parseInt(conventionerObj.toString());
        //删除用户信息
        int i = conventionerMapper.deleteByPrimaryKey(conventionerId);
        //删除用户申请记录
        AttendRecordExample example = new AttendRecordExample();
        AttendRecordExample.Criteria criteria = example.createCriteria();
        criteria.andConventionerIdEqualTo(conventionerId);
        int i1 = attendRecordMapper.deleteByExample(example);
        //删除用户分会场签到情况
        AttendRecordBranchExample example1 = new AttendRecordBranchExample();
        AttendRecordBranchExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andConventionerIdEqualTo(conventionerId);
        int i2 = attendRecordBranchMapper.deleteByExample(example1);

        if (i == 1) {
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), "删除用户信息成功");
        } else {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "删除用户信息失败");
        }
    }


    /**
     * 查询用户基础信息()
     */
    public ResultMsg selectConventionerBaseInfo(Map<String, Object> params) {
        //获取当前页数
        Object pageNumberObj = params.get("pageNumber");
        int pageNumber = Integer.parseInt(pageNumberObj.toString());
        //默认20页
        PageHelper.startPage(pageNumber, 20);

        ConventionerExample example = new ConventionerExample();
        ConventionerExample.Criteria criteria = example.createCriteria();
        criteria.andIdIsNotNull();
        //判断是否根据手机号查询
        Object phoneNumberObj = params.get("phoneNumber");
        if (phoneNumberObj != null && !"".equals(phoneNumberObj.toString())) {
            String phoneNumber = phoneNumberObj.toString();
            criteria.andPhoneNumberEqualTo(phoneNumber);
        }
        List<Conventioner> conventioners = conventionerMapper.selectByExample(example);

        if (conventioners != null && conventioners.size() > 0) {

            //获取总条数
            PageInfo<Conventioner> pageinfo = new PageInfo<>(conventioners);
            long pageTotal = pageinfo.getTotal();
            // 用总条数获取总页数
            pageTotal = (pageTotal + 20 - 1) / 20;

            Map<String, Object> result = new HashMap<>();
            result.put("dataList", conventioners);
            result.put("pageTotal", pageTotal);
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), result);
        } else {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "没有用户信息");
        }
    }


    /**
     * 查询所有已注册用户
     */
    public ResultMsg selectAllConventioners(Map<String, Object> params) {
        //执行分页操作
        PageHelperUtils.startPage(params);

        ConventionerExample example = new ConventionerExample();
        ConventionerExample.Criteria criteria = example.createCriteria();
        criteria.andIdIsNotNull();
        List<Conventioner> conventioners = conventionerMapper.selectByExample(example);


        if (conventioners != null && conventioners.size() > 0) {
            //获取总记录数
            PageInfo<Conventioner> pageinfo = new PageInfo<>(conventioners);
            long pageTotal = pageinfo.getTotal();

            //返回结果集
            Map<String, Object> result = new HashMap<>();
            result.put("dataList", conventioners);
            result.put("pageTotal", pageTotal);
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), result);
        } else {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "没有用户信息");
        }
    }

    /**
     * 修改密码接口
     */
    public ResultMsg editPassWord(Map<String, Object> params, HttpServletRequest request) {
        //首先对比验证码
        ResultMsg resultMsg = comparisonVerificationCode(params, request);
        if (resultMsg.getCode() != 200) {
            //验证码不一致
            return resultMsg;
        }
        //验证码一致，可以进行修改密码的操作
        //获取与会者手机号
        Object phoneNumberObj = params.get("phoneNumber");
        //校验手机号参数是否为空
        if (phoneNumberObj == null) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "手机号不可为空");
        }
        String phoneNumber = phoneNumberObj.toString();
        //去数据库查询该与会者信息
        Conventioner conventionerByPhoneNumber = getConventionerByPhoneNumber(phoneNumber);
        if (conventionerByPhoneNumber == null) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "找不到指定会员");
        }
        //获取新密码
        Object newPassWordObj = params.get("newPassWord");
        if (newPassWordObj == null) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "新密码不可为空");
        }
        String newPassWord = newPassWordObj.toString();

        //修改密码
        conventionerByPhoneNumber.setPassword(newPassWord);
        int i = conventionerMapper.updateByPrimaryKeySelective(conventionerByPhoneNumber);
        if (i == 1) {
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), "修改密码成功");
        } else {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "修改密码失败");
        }
    }

    /**
     * 与会者登录接口
     */
    public ResultMsg login(Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        //首先对比验证码(当前版本，登录不需要验证码)
//        ResultMsg resultMsg = comparisonVerificationCode(params, request);
//        if (resultMsg.getCode() != 200) {
//            //验证码不一致
//            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "验证码不一致，请重新获取验证码");
//        }
        //然后将前端传递过来的信息和数据库中查询的信息进行比对，然后返回结果，看是否登录；
        //获取与会者手机号
        Object phoneNumberObj = params.get("phoneNumber");
        //校验手机号参数是否为空
        if (phoneNumberObj == null) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "手机号不可为空");
        }
        String phoneNumber = phoneNumberObj.toString();

        //去数据库查询该与会者信息
        Conventioner conventionerByPhoneNumber = getConventionerByPhoneNumber(phoneNumber);
        if (conventionerByPhoneNumber == null) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "找不到指定会员");
        }
        //获取与会者密码
        Object passwordObj = params.get("password");
        if (passwordObj == null) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "密码不可为空");
        }
        String password = passwordObj.toString();
        //进行比对
        String passwordInDataSource = conventionerByPhoneNumber.getPassword();
        if (!password.equals(passwordInDataSource)) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "密码错误");
        } else {
            //登录成功之后，将用户信息存入cookie，用于保持登录
            //将用户转换为json字符串，并指定编码集防止乱码
            HttpSession session = request.getSession();
            Cookie cookie = null;
            if ("0123456789".equals(phoneNumber)) {
                //用于前台跳转manage页面时的判断
                session.setAttribute("adminUser", conventionerByPhoneNumber);
                cookie = new Cookie("admin", "adminUser");
            } else {
                session.setAttribute("user", conventionerByPhoneNumber);
                cookie = new Cookie("user", "normalUser");
            }

            cookie.setPath("/");
            //设置cookie的有效期为20分钟
            cookie.setMaxAge(20 * 60);
            response.addCookie(cookie);

            //返回用户ID用于申请会议时根据用户ID查询会议对象，返回手机号用于前台用户登录的判断
            Map<String, Object> result = new HashMap<>();
            result.put("phone", phoneNumber);
            result.put("Id", conventionerByPhoneNumber.getId());

            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), result);
        }
    }

    /**
     * 与会者注册接口
     */
    public ResultMsg register(Map<String, Object> params, HttpServletRequest request) {
        //比对验证码；
        ResultMsg resultMsg = comparisonVerificationCode(params, request);
        if (resultMsg.getCode() != 200) {
            //session中的验证码和前台传递的验证码不一致；
            return resultMsg;
        }
        //验证码一致，开始注册步骤
        //获取与会者手机号，昵称，密码，创建时间
        //获取手机号
        Object phoneNumberObj = params.get("phoneNumber");
        //校验手机号参数是否为空
        if (phoneNumberObj == null) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "手机号不可为空");
        }
        String phoneNumber = phoneNumberObj.toString();
        Object nameObj = params.get("name");
        if (nameObj == null) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "与会者名称不可为空");
        }
        String name = nameObj.toString();
        Object passwordObj = params.get("password");
        if (passwordObj == null) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "密码不可为空");
        }
        String password = passwordObj.toString();

        Conventioner conventioner = new Conventioner();
        conventioner.setName(name);
        conventioner.setPassword(password);
        conventioner.setPhoneNumber(phoneNumber);
        conventioner.setCreateTime(new Date());

        //注册与会者信息
        int i = conventionerMapper.insert(conventioner);

        if (i == 1) {
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), "注册成功");
        } else {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "注册失败");
        }
    }

    /**
     * 比对sesssion中的验证码和前端传递过来的验证码
     *
     * @return
     */
    public ResultMsg comparisonVerificationCode(Map<String, Object> params, HttpServletRequest request) {
        HttpSession session = request.getSession();

        Object code_phoneNumberObj = null;
        //从sesssion中获取手机号
        //通过不同的请求路径，获取sesssion中不同的key
        String requestURL = request.getRequestURL().toString();
        if (requestURL.contains("/register")) {
            //获取注册时后台保存的验证码接收手机号
            code_phoneNumberObj = session.getAttribute("register_code_phoneNumber");
        } else if (requestURL.contains("/editPassWord")) {
            //获取重置密码时后台保存的验证码接收手机号
            code_phoneNumberObj = session.getAttribute("editPassword_code_phoneNumber");
        }


        if (code_phoneNumberObj == null) {
            //已超时
            return new ResultMsg(502, ResultStatusCode.EORROR.getMsg(), "超时，请重新获取验证码");
        }
        String code_phoneNumber = code_phoneNumberObj.toString();

        //获取手机号，用于从session中获取验证码,以及比对手机号
        Object phoneNumberObj = params.get("phoneNumber");
        //校验手机号参数是否为空
        if (phoneNumberObj == null) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "手机号不可为空");
        }
        String phoneNumber = phoneNumberObj.toString();

        //比较两次的手机号是否一致
        if (!phoneNumber.equals(code_phoneNumber)) {
            return new ResultMsg(501, ResultStatusCode.EORROR.getMsg(), "两次手机号不一致");
        }

        //获取验证码，跟session中的验证码进行比对
        Object verificationCodeObj = params.get("verificationCode");
        if (verificationCodeObj == null) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "验证码不可为空");
        }
        String verificationCode = verificationCodeObj.toString();

        //从session中获取验证码
        Object codeInSession = session.getAttribute(phoneNumber);
        if (codeInSession == null) {
            //验证码已失效
            return new ResultMsg(502, ResultStatusCode.EORROR.getMsg(), "验证码已失效，请重新获取验证码");
        }
        String verificationCodeInSession = codeInSession.toString();
        if (!verificationCodeInSession.equals(verificationCode)) {
            //验证码不一致
            return new ResultMsg(502, ResultStatusCode.EORROR.getMsg(), "验证码不一致，请重新获取验证码");
        } else {
            //比对验证码一致后，将session置空
            session.invalidate();
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), "验证码一致,可以进行下一步操作");
        }
    }

    /**
     * 校验手机号，手机号是否符合格式，校验手机号是否为未注册状态
     */

    public ResultMsg matchPhoneNumber(Map<String, Object> params) {
        Object phoneNumberObj = params.get("phoneNumber");
        String phoneNumber = null;
        //校验手机号参数是否为空
        if (phoneNumberObj != null) {
            phoneNumber = phoneNumberObj.toString();
        } else {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "手机号不可为空");
        }
        //校验手机号是否符合格式
        Boolean matchPhoneNumber = PhoneNumberUtils.matchPhoneNumber(phoneNumber);
        //查询手机号是否已经注册
        Conventioner conventioner = getConventionerByPhoneNumber(phoneNumber);

        //根据前端传递的状态判断，到底要进行手机号未注册校验还是手机号已注册校验
        Object judgeCodeObj = params.get("judgeCode");
        if (judgeCodeObj == null) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "判断状态码不可为空");
        }
        String judgeCode = judgeCodeObj.toString();
        if ("0".equals(judgeCode)) {
            //进行手机号未注册判断
            ResultMsg resultMsg = phoneNumberUnResgitered(matchPhoneNumber, conventioner);
            return resultMsg;
        } else if ("1".equals(judgeCode)) {
            //进行手机号已注册判断
            ResultMsg resultMsg = phoneNumberResgitered(matchPhoneNumber, conventioner);
            return resultMsg;
        } else {
            //状态码错误
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "状态码错误");
        }
    }

    /**
     * 手机号未注册判断
     *
     * @return
     */
    public ResultMsg phoneNumberUnResgitered(Boolean matchPhoneNumber, Conventioner conventioner) {
        if (matchPhoneNumber == true && conventioner == null) {
            //手机号格式正确，并且还没有注册过
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), "手机号可以使用");
        } else {
            if (matchPhoneNumber != true && conventioner == null) {
                //手机号格式不正确
                return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "手机号格式不正确");
            } else if (matchPhoneNumber == true && conventioner != null) {
                //手机号已经注册过
                return new ResultMsg(501, ResultStatusCode.EORROR.getMsg(), "手机号已注册");
            } else {
                //手机号格式不正确，同时该手机号已经注册；
                return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "手机号不可用");
            }
        }
    }

    /**
     * 手机号已注册判断
     *
     * @return
     */
    public ResultMsg phoneNumberResgitered(Boolean matchPhoneNumber, Conventioner conventioner) {
        if (matchPhoneNumber == true && conventioner != null) {
            //手机号格式正确，并且还没有注册过
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), "手机号可以使用");
        } else {
            if (matchPhoneNumber != true && conventioner != null) {
                //手机号格式不正确
                return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "手机号格式不正确");
            } else if (matchPhoneNumber == true && conventioner == null) {
                //手机号未注册
                return new ResultMsg(501, ResultStatusCode.EORROR.getMsg(), "手机号未注册，请先注册");
            } else {
                //手机号格式不正确，同时该手机号未注册；
                return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "手机号不可用");
            }
        }
    }

    /**
     * 根据手机号查询与会者
     */
    public Conventioner getConventionerByPhoneNumber(String phoneNumber) {
        ConventionerExample example = new ConventionerExample();
        ConventionerExample.Criteria criteria = example.createCriteria();
        criteria.andPhoneNumberEqualTo(phoneNumber);

        List<Conventioner> conventioners = conventionerMapper.selectByExample(example);
        Conventioner conventioner = null;
        if (conventioners != null && conventioners.size() > 0) {
            conventioner = conventioners.get(0);
        }
        return conventioner;
    }
}
